import time
from selectors import SelectSelector

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from  selenium.webdriver.support.select import Select
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
class Base():
    def __init__(self,driver):
        self.driver=driver

    def open_url(self,url):
        self.driver.get(url)

    def find_element(self,loc):
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver :driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            str=time.strftime("%Y%m%d%H%M%S",time.localtime())
            self.driver.save_screenshot(str+'jt.png')
            print(e)

    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    def click(self,loc):
        self.find_element(loc).click()

    def get_text(self,loc):
        return self.find_element(loc).text

# 滚动条，
    def scroll_To(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')
        self.driver.execute_script(f'window.scrlloTo(0,document.body.scrollHeight())')
# 弹框处理，
    def alert(self):
        self.driver.switch_to.alert.accept()
    # iframe处理，
    def frame(self,loc):
        self.driver.switch_to.frame(self.find_element(loc))
        self.driver.switch_to.default_content()
    # 切换页面，
    def page_click(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 鼠标事件，
    def action(self,loc):
        ActionChains(self.driver).move_to_element(self.find_element(loc)).perform()
        ActionChains(self.driver).double_click(self.find_element(loc)).perform()
        ActionChains(self.driver).context_click(self.find_element(loc)).perform()

    # 键盘事件，
    def key(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)
        self.find_element(loc).send_keys(Keys.CONTROL,'a')
        self.find_element(loc).send_keys(Keys.CONTROL,'c')
        self.find_element(loc).send_keys(Keys.CONTROL,'v')

    # 浏览器事件
    def browser(self):
        self.driver.refresh()
        self.driver.back()
        self.driver.close()

    def select_value(self,value,loc):
        Select(self.find_element(loc)).select_by_value(value)

    def select_text(self,text,loc):
        Select(self.find_element(loc)).select_by_visible_text(text)

    def select(self,index,loc):
        Select(self.find_element(loc)).select_by_index(index)

